#!/bin/bash

echo "========================================"
echo "   Flutter 调试应用权限授权工具"
echo "========================================"
echo ""

# 检查ADB是否可用
if ! command -v adb &> /dev/null; then
    echo "[错误] 未找到 ADB 工具"
    echo "请确保已安装 Android SDK 并将 platform-tools 添加到系统环境变量"
    exit 1
fi

echo "[步骤1] 检查设备连接..."
adb devices
echo ""

echo "[步骤2] 获取应用包名..."
PACKAGE_NAME="com.matrix.capp.matrix_capp.debug"
echo "包名: $PACKAGE_NAME"
echo ""

echo "[步骤3] 授予安装来源权限..."
adb shell appops set $PACKAGE_NAME REQUEST_INSTALL_PACKAGES allow
if [ $? -ne 0 ]; then
    echo "[提示] 应用可能尚未安装，继续执行其他授权..."
else
    echo "[成功] 安装来源权限已授予"
fi
echo ""

echo "[步骤4] 授予其他常用权限..."
adb shell pm grant $PACKAGE_NAME android.permission.READ_EXTERNAL_STORAGE 2>/dev/null
adb shell pm grant $PACKAGE_NAME android.permission.WRITE_EXTERNAL_STORAGE 2>/dev/null
adb shell pm grant $PACKAGE_NAME android.permission.CAMERA 2>/dev/null
adb shell pm grant $PACKAGE_NAME android.permission.ACCESS_FINE_LOCATION 2>/dev/null
adb shell pm grant $PACKAGE_NAME android.permission.ACCESS_COARSE_LOCATION 2>/dev/null
echo "[完成] 常用权限授予完成"
echo ""

echo "[步骤5] 重启应用（如果已安装）..."
adb shell am force-stop $PACKAGE_NAME
echo "[完成] 应用已重启"
echo ""

echo "========================================"
echo "授权完成！现在可以开始调试应用了"
echo "========================================"
echo ""
echo "提示：首次安装应用后，请再次运行此脚本进行授权"
